package launch.helpers;

import client.DbgAccount;
import launch.LoginServer;
import launch.world.WorldConnected;
import packet.creators.LoginPacket;
import tools.FileoutputUtil;
import tools.Pair;
import tools.Timer.PingTimer;
import tools.Timer.WorldTimer;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DbgLoginWorker {

    private static Runnable persister;
    private static final List<Pair<Integer, String>> IPLog = new LinkedList<Pair<Integer, String>>();
    private static final Lock mutex = new ReentrantLock();

    protected DbgLoginWorker() {
	persister = new PersistingTask();
	WorldTimer.getInstance().register(persister, 1800000L);
    }

    private static class PersistingTask implements Runnable {

	@Override
	public void run() {
	    final StringBuilder sb = new StringBuilder();

	    mutex.lock();
	    try {
		final String time = FileoutputUtil.CurrentReadable_Time();

		for (Pair<Integer, String> logentry : IPLog) {
		    sb.append("ACCID : ");
		    sb.append(logentry.getLeft());
		    sb.append(", IP : ");
		    sb.append(logentry.getRight());
		    sb.append(", TIME : ");
		    sb.append(time);
		    sb.append("\n");
		}
		IPLog.clear();
	    } finally {
		mutex.unlock();
	    }
	    FileoutputUtil.log(FileoutputUtil.IP_Log, sb.toString());
	}
    }

    public static void registerClient(final DbgAccount c) {
	if (c.finishLogin() == 0) {
	    c.getSession().write(LoginPacket.getAuthSuccessRequest(c));
            c.getSession().write(LoginPacket.getServerList(12, WorldConnected.getConnected()));
            c.getSession().write(LoginPacket.getEndOfServerList());
            c.send(LoginPacket.recommendWorld());
            c.send(LoginPacket.getLastWorld());
	    c.setIdleTask(PingTimer.getInstance().schedule(new Runnable() {

		public void run() {
		    c.getSession().close();
		}
	    }, 10 * 60 * 10000));
	} else {
	    c.getSession().write(LoginPacket.getLoginFailed(7));
	    return;
	}
	mutex.lock();
	try {
	    IPLog.add(new Pair<Integer, String>(c.getAccID(), c.getSession().getRemoteAddress().toString()));
	} finally {
	    mutex.unlock();
	}
    }
}
